package com.aiyige.page.test;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;


import org.greenrobot.eventbus.EventBus;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

/**
 * Created by xiachao on 2018/2/17.
 */

public class UdpReceiverService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        DatagramSocket dgSocket = null;
                        int port = TestQNPlayerPage.port;
                        if (dgSocket == null) {
                            dgSocket = new DatagramSocket(null);
                            dgSocket.setReuseAddress(true);
                            dgSocket.bind(new InetSocketAddress(port));
                        }
                        byte[] by = new byte[2048];
                        DatagramPacket packet = new DatagramPacket(by, by.length);
                        dgSocket.receive(packet);
                        String str = new String(packet.getData(), 0, packet.getLength());
                        System.out.println("接收到的数据为：" + str);
                        Log.v("XIACHAO", "已获取服务器端发过来的数据。。。。。" + str);
                        EventBus.getDefault().post(EventSTB.newBuilder().content(str).build());
                    } catch (Exception e) {
                        Log.v("XIACHAO", "我擦，出错了。。。。。" + e.toString());
                    }
                }
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }

    public void sendPlayInfo(Message msg) {

    }




    public class MyBinder extends Binder {

        public void call(Message msg) {
            sendPlayInfo(msg);
        }
    }


}